1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.collect.MapConstraintsTest.TestKeyException;
23 import com.google.common.collect.MapConstraintsTest.TestValueException;
24 import com.google.common.collect.testing.google.TestStringBiMapGenerator;
25
26 import junit.framework.TestCase;
27
28 import java.util.Map.Entry;
29
30
31
32
33
34
35
36 @GwtCompatible(emulated = true)
37 public class ConstrainedBiMapTest extends TestCase {
38
39 private static final String TEST_KEY = "42";
40 private static final String TEST_VALUE = "test";
41 private static final MapConstraint<String, String> TEST_CONSTRAINT = new TestConstraint();
42
43 public void testPutWithForbiddenKeyForbiddenValue() {
44 BiMap<String, String> map = MapConstraints.constrainedBiMap(
45 HashBiMap.<String, String> create(),
46 TEST_CONSTRAINT);
47 try {
48 map.put(TEST_KEY, TEST_VALUE);
49 fail("Expected IllegalArgumentException");
50 } catch (IllegalArgumentException expected) {
51
52 }
53 }
54
55 public void testPutWithForbiddenKeyAllowedValue() {
56 BiMap<String, String> map = MapConstraints.constrainedBiMap(
57 HashBiMap.<String, String> create(),
58 TEST_CONSTRAINT);
59 try {
60 map.put(TEST_KEY, "allowed");
61 fail("Expected IllegalArgumentException");
62 } catch (IllegalArgumentException expected) {
63
64 }
65 }
66
67 public void testPutWithAllowedKeyForbiddenValue() {
68 BiMap<String, String> map = MapConstraints.constrainedBiMap(
69 HashBiMap.<String, String> create(),
70 TEST_CONSTRAINT);
71 try {
72 map.put("allowed", TEST_VALUE);
73 fail("Expected IllegalArgumentException");
74 } catch (IllegalArgumentException expected) {
75
76 }
77 }
78
79 public static final class ConstrainedBiMapGenerator extends TestStringBiMapGenerator {
80 @Override
81 protected BiMap<String, String> create(Entry<String, String>[] entries) {
82 BiMap<String, String> bimap = MapConstraints.constrainedBiMap(
83 HashBiMap.<String, String> create(),
84 TEST_CONSTRAINT);
85 for (Entry<String, String> entry : entries) {
86 checkArgument(!bimap.containsKey(entry.getKey()));
87 bimap.put(entry.getKey(), entry.getValue());
88 }
89 return bimap;
90 }
91 }
92
93 private static final class TestConstraint implements MapConstraint<String, String> {
94 @Override
95 public void checkKeyValue(String key, String value) {
96 if (TEST_KEY.equals(key)) {
97 throw new TestKeyException();
98 }
99 if (TEST_VALUE.equals(value)) {
100 throw new TestValueException();
101 }
102 }
103
104 private static final long serialVersionUID = 0;
105 }
106 }
107